package com.shrio.lucene;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.File;
import java.io.IOException;

/**
 * Created by luojie on 2018/4/24.
 * 这个是精确查询
 */
public class SearcherTest2 {

    public static void main(String[] args) {
        try {
            //1、创建Directory
            Directory directory = FSDirectory.open(new File("G:\\index"));

            //创建索引读取器
            IndexReader reader= DirectoryReader.open(directory);
            //创建索引查询器
            IndexSearcher searcher=new IndexSearcher(reader);

            //这个是精确查询
            Query query = new TermQuery(new Term("content","小米"));
            //5、根据searcher搜索并返回TopDocs
            //表示返回前面10条
            TopDocs topDocs = searcher.search(query,10);
            //6、根据TopDocs获取ScoreDoc对象
            ScoreDoc[] scoreDocs = topDocs.scoreDocs;
            for(ScoreDoc sd : scoreDocs){
                //7、根据Searcher和ScordDoc对象获取具体的Document对象
                //获取这个文档的id
                int doc = sd.doc;
                Document document = searcher.doc(doc);
                //8、根据Document对象获取需要的值
                System.out.println("【找到】" + document.get("fileName") + "    " + document.get("path") + " .." + document.get("content"));
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
